<?php
namespace Modules\Backstage\Controllers;

class SwipeController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute(\Phalcon\Mvc\Dispatcher $dispatcher) {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');

		$service = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($service['code'] != 0) {
			$this -> response -> setJsonContent(['code'=>-1,'msg'=>$service['message'] ]) -> send();
			exit;
		}

		$this -> account::getAclInstance() -> check($this, $dispatcher, $service['model'] -> roles_id);
	}


	public function indexAction() {
		$query = $this -> request -> getQuery();
		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$service = $this -> swipe::getServiceInstance() -> pager(['order' => 'swipe_id DESC'], $query['limit'], $query['page']);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
	}

	public function createAction() {
		$post = $this -> request -> getPost();
		$post['create_time'] = time();
		$service = $this -> swipe::getServiceInstance() -> create($post);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'创建成功']);
	}

	public function deleteAction($id) {
		$service = $this -> swipe::getServiceInstance() -> delete($id);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'删除成功']);
	}
}